/*
 * Licensed to the Apache Software Foundation (ASF) under one or more
 * contributor license agreements.  See the NOTICE file distributed with
 * this work for additional information regarding copyright ownership.
 * The ASF licenses this file to You under the Apache License, Version 2.0
 * (the "License"); you may not use this file except in compliance with
 * the License.  You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.lmx.repoDomain.repository;

import com.lmx.common.constants.CommonConstants;
import com.lmx.persistence.service.NursingService;
import com.lmx.repoDomain.exception.BusinessException;
import com.lmx.repoDomain.tmodel.NursingPlanExecute;
import io.katharsis.repository.annotations.JsonApiResourceRepository;
import io.katharsis.repository.annotations.JsonApiSave;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;

@JsonApiResourceRepository(NursingPlanExecute.class)
@Component
public class NursingPlanExeRepository extends BaseRepository<NursingPlanExecute> {

	@Autowired
	private NursingService nursingService;

	@PostConstruct
	public void init() {
		dslJpaService.setEntityClass(NursingPlanExecute.class);
	}

	@Override
	@JsonApiSave
	public NursingPlanExecute save(NursingPlanExecute data) {
		if (data.getId() == null) {
			if (data.getDetail() == null && data.getItemProject() == null) {
				throw new BusinessException(null, CommonConstants.ERROR_CODE.REPEAT_ERROR.label(), null);
			}
			//定时任务 如果已经被执行加验证
			if(data.getDetail()!=null){
				int addFlag = nursingService.checkPlanDetailExeRelations(data.getDetail());
				if (addFlag > 0) {
					data.setErrcode(14);
					throw new BusinessException(null, CommonConstants.ERROR_CODE.ADD_ERROR.label(), null);
				}
			}
			nursingService.addPlanExe(data);
		} else {
			if (data.getDelStatus() == 1) {
				//同时删除相应的增值服务账单
				nursingService.deleteNursingPlanExecute(data);
			} else {
				nursingService.addPlanExe(data);
			}
		}
		return data;
	}

}
